<template>
  <div class="container">
    <!-- 登录区域 -->
    <div class="content">
      <!-- 配图 -->
      <!-- <div class="pic"></div> -->
      <!-- 表单 -->
      <div class="field">
        <h2 class="title">登录</h2>
        <!-- 表单 -->
        <div class="form-cont">
          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="LoginRules"
            class="login-form"
          >
            <!-- 账号密码登录 -->
            <el-form-item prop="username" label="账号：" label-width="80px">
              <el-input
                v-model="loginForm.username"
                type="text"
                auto-complete="off"
                placeholder="学号/工号/用户名"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码：" label-width="80px">
              <el-input
                v-model="loginForm.password"
                type="password"
                auto-complete="off"
                placeholder="密码"
                @keyup.enter.native="handleLogin"
              >
              </el-input>
            </el-form-item>
            <div class="verification">
              <span>为了保证您的正常访问，请进行如下验证：</span>
              <jc-range
                :status="'false'"
                :successFun="() => (loginForm.checkFlag = true)"
                :errorFun="() => (loginForm.checkFlag = false)"
              ></jc-range>
            </div>
            <!-- 下方的登录按钮 -->
            <el-form-item style="text-align: center">
              <el-button
                :loading="loading"
                size="medium"
                type="primary"
                @click.native.prevent="handleLogin"
              >
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- <div class="otherbtn">
          <a href="#">扫码登录</a>
          <a href="#">找回密码</a>
        </div> -->
      </div>
    </div>
    <!-- footer -->
  </div>
</template>

<script>
import { socialAuthRedirect } from "@/api/login";
import { SystemUserSocialTypeEnum } from "@/utils/constants";
import { getTenantIdByName } from "@/api/system/tenant";
import {
  getPassword,
  getRememberMe,
  getTenantName,
  getUsername,
  removePassword,
  removeRememberMe,
  removeTenantName,
  removeUsername,
  setPassword,
  setRememberMe,
  setTenantId,
  setTenantName,
  setUsername,
} from "@/utils/auth";
import JcRange from "./JcRange.vue";

export default {
  components: { JcRange },
  name: "Login",
  data() {
    return {
      codeUrl: "",
      captchaEnable: true,
      mobileCodeTimer: 0,
      loginForm: {
        loginType: "uname",
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        checkFlag: false,
        tenantName: "系统租户",
      },
      scene: 21,

      LoginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" },

          {
            validator: (rule, value, callback) => {
              // debugger
              getTenantIdByName(/*this.loginForm.tenantName*/"系统租户").then((res) => {
                const tenantId = res.data;
                if (tenantId && tenantId >= 0) {
                  // 设置租户
                  setTenantId(tenantId);
                  callback();
                } else {
                  callback("租户不存在");
                }
              });
            },
            trigger: "blur",
          },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        code: [
          { required: true, trigger: "change", message: "验证码不能为空" },
        ],
        mobile: [
          { required: true, trigger: "blur", message: "手机号不能为空" },
          {
            validator: function (rule, value, callback) {
              if (
                /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(
                  value
                ) === false
              ) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],

      },
      loading: false,
      redirect: undefined,
      // 枚举
      SysUserSocialTypeEnum: SystemUserSocialTypeEnum,
    };
  },
  // watch: {
  //   $route: {
  //     handler: function(route) {
  //       this.redirect = route.query && route.query.redirect;
  //     },
  //     immediate: true
  //   }
  // },
  created() {
    // 重定向地址
    this.redirect = this.$route.query.redirect;
    this.getCookie();
  },
  methods: {
    getCookie() {
      const username = getUsername();
      const password = getPassword();
      const rememberMe = getRememberMe();
      const tenantName = getTenantName();
      this.loginForm = {
        ...this.loginForm,
        username: username ? username : this.loginForm.username,
        password: password ? password : this.loginForm.password,
        rememberMe: rememberMe ? getRememberMe() : false,
        tenantName: tenantName ? tenantName : this.loginForm.tenantName,
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          if (!this.loginForm.checkFlag) {
            this.$message.error("请先滑动滑块进行验证");
            return;
          }
          this.loading = true;
          // 设置 Cookie
          if (this.loginForm.rememberMe) {
            setUsername(this.loginForm.username);
            setPassword(this.loginForm.password);
            setRememberMe(this.loginForm.rememberMe);
            setTenantName(this.loginForm.tenantName);
          } else {
            removeUsername();
            removePassword();
            removeRememberMe();
            removeTenantName();
          }

          // 发起登陆
          // console.log("发起登录", this.loginForm);
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" }).catch(() => { });
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    doSocialLogin(socialTypeEnum) {
      // 设置登录中
      this.loading = true;
      // 计算 redirectUri
      const redirectUri =
        location.origin +
        "/social-login?type=" +
        socialTypeEnum.type +
        "&redirect=" +
        (this.redirect || "/"); // 重定向不能丢
      // const redirectUri = 'http://127.0.0.1:48080/api/gitee/callback';
      // const redirectUri = 'http://127.0.0.1:48080/api/dingtalk/callback';
      // 进行跳转
      socialAuthRedirect(
        socialTypeEnum.type,
        encodeURIComponent(redirectUri)
      ).then((res) => {
        // console.log(res.url);
        window.location.href = res.data;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/login.scss";

.oauth-login {
  display: flex;
  align-items: cen;
  cursor: pointer;
}
.oauth-login-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
}
.oauth-login-item img {
  height: 25px;
  width: 25px;
}
.oauth-login-item span:hover {
  text-decoration: underline red;
  color: red;
}
</style>

<style lang="scss">
.login-form .el-form-item__label {
  color: #fff;
  font-size: 18px;
  font-weight: normal;
}
.login-form .el-form-item__label::before {
  content: "" !important;
}
.login-form .el-input__inner {
  color: #fff;
  background: transparent;
  border-color: #fff;
  border-radius: 0;
}
.login-form .el-button {
  width: 90px;
  line-height: 36px;
  padding: 0;
  font-size: 16px;
  background-color: #169bd5;
  border-color: #169bd5;
}
</style>
